<?php

namespace App\Http\Controllers\Mp;

use App\Contract\ContractStatus;
use App\Http\Controllers\Controller;
use App\Model\Bill;
use App\Model\Contract;
use App\Model\House;
use App\Utils\Result;
use App\Utils\Token;
use Guzzle\Http\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class IndexController extends Controller
{
    public function business(): \Illuminate\Http\JsonResponse
    {
        $data = [
           'contract' => [
               'willExpire' => 0, // 将到期合同
               'expired' => 0, // 逾期合同
           ],
            'bill' => [
                'amount' => 0, // 待收金额
                'failAmount' => 0, // 逾期金额
            ],
            'house' => [
                'total' => 0,
                'hired' => 0, // 出租
                'vacant' => 0, // 空置
                'percent' => 0, // 出租率
            ],
            'amount' => [
                'month' => [
                    'bill' => 0,
                    'paid' => 0,
                ],
                'lastMonth' => [
                    'bill' => 0, // 预期
                    'paid' => 0, // 实际收入
                ]
            ]
        ];
        $user = $this->getUser();
        if($user && $user->type == 'admin'){
            $houses = House::query()->whereIn('house_class_id',json_decode($user->class_id))
                ->pluck('id')->toArray();
            $data['contract']['willExpire'] = Contract::query()->whereIn('house_id', $houses)
                ->where('expired_at', '<', now()->addDays(30)->toDateString())
                ->where('status', ContractStatus::YIQIANYUE)
                ->count();
            // 逾期合同 已到期未退房合同
            $data['contract']['expired'] = Contract::query()->whereIn('house_id', $houses)
                ->where('expired_at', '<', now()->toDateString())
                ->where('status', ContractStatus::YIQIANYUE)
                ->count();
            // 待收金额30天内
            $data['bill']['amount'] = Bill::query()->whereIn('house_id', $houses)
                ->where('pay_date', '<', now()->addDays(30)->toDateString())
                ->where('is_paid', 0)
                ->where('is_close', 0)
                ->sum('amount');
            // 逾期金额
            $data['bill']['failAmount'] = Bill::query()->whereIn('house_id', $houses)
                ->where('pay_date', '<', now()->toDateString())
                ->where('is_paid', 0)
                ->where('is_close', 0)
                ->sum('amount');
            // 房源
            $data['house']['total'] = House::query()->whereIn('id', $houses)->count();
            $data['house']['hired'] = House::query()->whereIn('id', $houses)
                ->whereHas('contract', function($q) {
                    $q->where('status', ContractStatus::YIQIANYUE);
                })
                ->count();
            $data['house']['vacant'] = $data['house']['total'] - $data['house']['hired'];
            if ($data['house']['total'] > 0 && $data['house']['hired'] > 0) {
                $data['house']['percent'] = (float) number_format(($data['house']['hired'] / $data['house']['total']) * 100, 2);
            }
            // 本月
            $data['amount']['month']['bill'] = Bill::query()->whereIn('house_id', $houses)
                ->whereYear('pay_date', date('Y'))->whereMonth('pay_date', date('m'))
                ->where('is_close', 0)
                ->sum('amount');
            $data['amount']['month']['paid'] = Bill::query()->whereIn('house_id', $houses)
                ->whereYear('pay_date', date('Y'))->whereMonth('pay_date', date('m'))
                ->where('is_paid', 1)
                ->where('is_close', 0)
                ->sum('amount');
            // 上月
            $data['amount']['lastMonth']['bill'] = Bill::query()->whereIn('house_id', $houses)
                ->whereYear('pay_date', now()->subMonth()->year)->whereMonth('pay_date', now()->subMonth()->month)
                ->where('is_close', 0)
                ->sum('amount');
            $data['amount']['lastMonth']['paid'] = Bill::query()->whereIn('house_id', $houses)
                ->whereYear('pay_date', now()->subMonth()->year)->whereMonth('pay_date', now()->subMonth()->month)
                ->where('is_paid', 1)
                ->where('is_close', 0)
                ->sum('amount');
        }else{
            if ($this->getBusinessId()) {
                // 将到期合同 30天内
                $data['contract']['willExpire'] = Contract::query()->where('business_id', $this->getBusinessId())
                    ->where('expired_at', '<', now()->addDays(30)->toDateString())
                    ->where('status', ContractStatus::YIQIANYUE)
                    ->count();
                // 逾期合同 已到期未退房合同
                $data['contract']['expired'] = Contract::query()->where('business_id', $this->getBusinessId())
                    ->where('expired_at', '<', now()->toDateString())
                    ->where('status', ContractStatus::YIQIANYUE)
                    ->count();
                // 待收金额30天内
                $data['bill']['amount'] = Bill::query()->where('business_id', $this->getBusinessId())
                    ->where('pay_date', '<', now()->addDays(30)->toDateString())
                    ->where('is_paid', 0)
                    ->where('is_close', 0)
                    ->sum('amount');
                // 逾期金额
                $data['bill']['failAmount'] = Bill::query()->where('business_id', $this->getBusinessId())
                    ->where('pay_date', '<', now()->toDateString())
                    ->where('is_paid', 0)
                    ->where('is_close', 0)
                    ->sum('amount');
                // 房源
                $data['house']['total'] = House::query()->where('business_id', $this->getBusinessId())->count();
                $data['house']['hired'] = House::query()->where('business_id', $this->getBusinessId())
                    ->whereHas('contract', function($q) {
                        $q->where('status', ContractStatus::YIQIANYUE);
                    })
                    ->count();
                $data['house']['vacant'] = $data['house']['total'] - $data['house']['hired'];
                if ($data['house']['total'] > 0 && $data['house']['hired'] > 0) {
                    $data['house']['percent'] = (float) number_format(($data['house']['hired'] / $data['house']['total']) * 100, 2);
                }
                // 本月
                $data['amount']['month']['bill'] = Bill::query()->where('business_id', $this->getBusinessId())
                    ->whereYear('pay_date', date('Y'))->whereMonth('pay_date', date('m'))
                    ->where('is_close', 0)
                    ->sum('amount');
                $data['amount']['month']['paid'] = Bill::query()->where('business_id', $this->getBusinessId())
                    ->whereYear('pay_date', date('Y'))->whereMonth('pay_date', date('m'))
                    ->where('is_paid', 1)
                    ->where('is_close', 0)
                    ->sum('amount');
                // 上月
                $data['amount']['lastMonth']['bill'] = Bill::query()->where('business_id', $this->getBusinessId())
                    ->whereYear('pay_date', now()->subMonth()->year)->whereMonth('pay_date', now()->subMonth()->month)
                    ->where('is_close', 0)
                    ->sum('amount');
                $data['amount']['lastMonth']['paid'] = Bill::query()->where('business_id', $this->getBusinessId())
                    ->whereYear('pay_date', now()->subMonth()->year)->whereMonth('pay_date', now()->subMonth()->month)
                    ->where('is_paid', 1)
                    ->where('is_close', 0)
                    ->sum('amount');
            }
        }

        return Result::success($data);
    }

    public function tenant(Request $request): \Illuminate\Http\JsonResponse
    {
        $data = [
            'contract' => [],
            'bills' => [],
            'sign_count' => 0, // 待签约
            'pay_bill_count' => 0
        ];

        $contract_id = $request->input('contract_id');

        $user = Token::getUser();
        if ($user) {
            $contractList = Contract::query()->whereHas('contractTenant', function($q) use ($user) {
                $q->where('mobile', $user->mobile);
            })->where('status', ContractStatus::YIQIANYUE)
                ->latest()->with('contractRent', 'house', 'house.dianbiao')
                ->take(100)
                ->where(function($q) use ($contract_id) {
                    if ($contract_id) {
                        $q->where('id', $contract_id);
                    }
                })
                ->get();

            foreach ($contractList as &$contract) {
                if (!$contract->house) {
                    continue;
                }
                $contract->house->dianfei = $contract->house->dianfei * 1;
                $data['contract'][] = [
                    'id' => $contract->id,
                    'business_id' => $contract->business_id,
                    'house_id' => $contract->house_id,
                    'name' => $contract->house->estate_name . $contract->house->name,
                    'expire_days' => now()->diffInDays(Carbon::createFromFormat('Y-m-d', $contract->expired_at)),
                    'fail_bill_count' => $contract->bills()->where('is_paid', 0)->where('is_close', 0)
                        ->where('pay_date', '<', Carbon::now()->toDateString())->count(),
                    'dianbiao' => $contract->house->dianbiao ?? null,
                ];
                if (!$contract_id) {
                    $contract_id = $contract->id;
                }
            }

            $data['bills'] = Bill::query()->where('mobile', $user->mobile)
                ->whereHas('house')
                ->where('pay_date', '<', now()->addDays(15)->toDateString())
                ->with('house')
                ->where('is_paid', 0)
                ->where('is_close', 0)
                ->orderBy('pay_date')
                ->where(function($q) use ($contract_id) {
                    if ($contract_id) {
                        $q->where('contract_id', $contract_id);
                    }
                })
                ->get()->toArray();

            $data['sign_count'] = Contract::query()->whereHas('contractTenant', function($q) use ($user) {
                $q->where('mobile', $user->mobile);
            })->where('status', ContractStatus::DAIQIANYUE)->count();
            $data['pay_bill_count'] = Bill::query()->where('mobile', $user->mobile)
                ->whereHas('house')
                ->where('is_paid', 0)
                ->where('is_close', 0)
                ->orderBy('pay_date')
                ->where(function($q) use ($contract_id) {
                    if ($contract_id) {
                        $q->where('contract_id', $contract_id);
                    }
                })->count();
        }

        return Result::success($data);
    }

    public function getAddress(Request $request)
    {
        $key = 'M27BZ-SDWW7-W54XC-H2WB5-NIHC3-NWFNZ';
        $location = $request->input('location');

        $url = 'https://apis.map.qq.com/ws/geocoder/v1/?location=' . $location . '&key=' . $key;

        $response = Http::get($url);
        $result = json_decode($response->body());
        Log::info('location-----'.$result);
        return Result::success($result);
    }
}
